import pytest
from tools.app_manager import AppManager
from config.settings import APP_CONFIG
from package.enter_production_info import enter_production_info
from package.domain_login import domain_login


@pytest.fixture(scope="class")
def class_app_manager(request):
    """
    类级别应用管理器：启动一次，测试类结束后关闭
    不自动关闭，由测试类控制（或通过 finalizer）
    """
    manager = AppManager(exe_path=APP_CONFIG["exe_path"])
    manager.start_app()

    # 注册关闭函数，确保即使出错也会清理
    def finalize():
        manager.close_app()

    request.addfinalizer(finalize)

    return manager


@pytest.fixture(scope="class")
def main_window_with_production(class_app_manager, production_info):
    """类级别：设置生产信息并进入主界面"""
    login_win = class_app_manager.connect_to_login()
    enter_production_info(
        login_win,
        production_info["项目号"],
        production_info["工单号"],
        production_info["工位站"]
    )
    return class_app_manager.connect_to_main()


@pytest.fixture(scope="class")
def relation_inquiry_window(main_window_with_production, class_app_manager):
    """类级别：进入查询/解绑界面"""
    return domain_login(class_app_manager)